//商品失效检测

const Router = require('koa-router')
const { query,constInsert,exeTrans,constUpdate,paging,constructWhere } = require('../db')
const { getRes } = require('../res')
let request = require('request');
let content = new Router()

function checkmcn(url,qry){
    return new Promise(function(resolve, reject) {
        request.post(
            {
            url:url, 
            form:qry
        }, function(error, response, body) {
            if (response.statusCode == 200) {
                var res = JSON.parse(body);
                // console.log(res);
                resolve(res.data);
            }
        })
    });
}

function reSetData(dataList,num) {
    let arr = [];
    let len = dataList.length;
    for (let i = 0; i < len; i += num) {
        arr.push(dataList.slice(i, i + num));
    }
    return arr;
}

content.post('/check_self_mcn', async(ctx) => {
    try {
        let qry = ctx.request.body;
        let jd_mcn = qry.jd_mcn;
        let tb_mcn = qry.tb_mcn;
        console.log(qry);

        //接口调用订单侠https://www.dingdanxia.com/
        var apikey= "接口认证参数";
        var jdurl = 'http://api.tbk.dingdanxia.com/jd/query_goods_promotioninfo';
        var tburl = "http://api.tbk.dingdanxia.com/tbk/item_info";
        let list = [];
        let tranFunc = async (conn) => {//执行事务
            try{
                //京东
                let dis_jd_skuid = jd_mcn;
                let mcn_list_jd = [];
                for(var i=0;i<dis_jd_skuid.length;i++){
                    mcn_list_jd.push(dis_jd_skuid[i]);
                }
                
                let jd_list = [];
                let jd_mcn_qry = reSetData(mcn_list_jd,100);
                console.log(mcn_list_jd);
                console.log(jd_mcn_qry);
                for(var i=0;i<jd_mcn_qry.length;i++){
                    let f = {
                        apikey:apikey,
                        skuIds:jd_mcn_qry[i].join()
                    };
                    let l = await checkmcn(jdurl,f);
                    console.log(l);
                    jd_list = jd_list.concat(l.map(function(v){return v.skuId}));
                    console.log(jd_list);
                }
                
                //淘宝
                console.log("mcn_list_tb*************************");
                let dis_tb_skuid = tb_mcn;
                let mcn_list_tb = [];
                for(var i=0;i<dis_tb_skuid.length;i++){
                    mcn_list_tb.push(dis_tb_skuid[i]);
                }
                console.log(mcn_list_tb.length);
                let tb_list = [];
                let tb_mcn_qry = reSetData(mcn_list_tb,40);
                for(var i=0;i<tb_mcn_qry.length;i++){
                    let f = {
                        apikey:apikey,
                        num_iids:tb_mcn_qry[i].join()
                    };
                    let l = await checkmcn(tburl,f);
                    console.log(f);
                    tb_list = tb_list.concat(l.map(function(v){return v.num_iid}));
                }
                console.log(tb_list.length);
                
                let mcn_obj = {
                    tb_list:tb_list,
                    jd_list:jd_list
                }

                return Promise.resolve(mcn_obj);
            }catch (e){
                return Promise.reject(e);
            }
        }
        list = await exeTrans(tranFunc);
        
        ctx.response.body = getRes(0,list);
    }catch (e){
        console.log(e);
        ctx.response.body = getRes(2,e);
    }
})

content.post('/check_con_mcn', async(ctx) => {
    try {
        let sql = "select * from userinfo where id=? and lasttime>now() and status>=0";
        let user = await query(sql,ctx.user.id);
        if(user.length==0){
            return ctx.response.body = getRes(8);
        }

         //接口调用订单侠https://www.dingdanxia.com/
        var apikey= "接口认证参数";
        var jdurl = 'http://api.tbk.dingdanxia.com/jd/query_goods_promotioninfo';
        var tburl = "http://api.tbk.dingdanxia.com/tbk/item_info";
        let list = [];
        let tranFunc = async (conn) => {//执行事务
            try{
                //京东
                await query(`update mcn set mcn_isvail = 0 where user_id=? and mcn_tag = '京东' and content_id is not null`,ctx.user.id);
                let dis_jd_skuid = await query(`select DISTINCT mcn_skuid from mcn where user_id=? and mcn_tag = '京东' and content_id is not null`,ctx.user.id);
                let mcn_list_jd = [];
                for(var i=0;i<dis_jd_skuid.length;i++){
                    mcn_list_jd.push(dis_jd_skuid[i].mcn_skuid);
                }
                
                let jd_list = [];
                let jd_mcn_qry = reSetData(mcn_list_jd,100);
                for(var i=0;i<jd_mcn_qry.length;i++){
                    let f = {
                        apikey:apikey,
                        skuIds:jd_mcn_qry[i].join()
                    };
                    let l = await checkmcn(jdurl,f);
                    jd_list = jd_list.concat(l);
                }
                
                for(var i=0;i<jd_list.length;i++){
                    await query(`update mcn set mcn_isvail = 1 where mcn_skuid=? and mcn_tag = '京东'`,jd_list[i].skuId);
                }
                
                //淘宝
                console.log("mcn_list_tb*************************");
                await query(`update mcn set mcn_isvail = 0 where user_id=? and mcn_tag = '淘宝' and content_id is not null`,ctx.user.id);
                let dis_tb_skuid = await query(`select DISTINCT mcn_skuid from mcn where user_id=? and mcn_tag = '淘宝' and content_id is not null`,ctx.user.id);
                let mcn_list_tb = [];
                for(var i=0;i<dis_tb_skuid.length;i++){
                    mcn_list_tb.push(dis_tb_skuid[i].mcn_skuid);
                }
                console.log(mcn_list_tb.length);
                let tb_list = [];
                let tb_mcn_qry = reSetData(mcn_list_tb,40);
                for(var i=0;i<tb_mcn_qry.length;i++){
                    let f = {
                        apikey:apikey,
                        num_iids:tb_mcn_qry[i].join()
                    };
                    let l = await checkmcn(tburl,f);
                    console.log(f);
                    tb_list = tb_list.concat(l);
                }
                console.log(tb_list.length);
                for(var i=0;i<tb_list.length;i++){
                    await query(`update mcn set mcn_isvail = 1 where mcn_skuid=? and mcn_tag = '淘宝'`,tb_list[i].num_iid);
                }
                return Promise.resolve(0);
            }catch (e){
                return Promise.reject(e);
            }
        }
        list = await exeTrans(tranFunc);
        if(list==null){
            list =[];
        }
        ctx.response.body = getRes(0,list);
    }catch (e){
        console.log(e);
        ctx.response.body = getRes(2,e);
    }
})

content.post('/getall_id_byuser', async(ctx) => {
    try {
        let res = await query(`select itemid from content where user_id =? order by id desc`,ctx.user.id);
        let list = [];
        res.forEach(item => {
            list.push(item.itemid);
        });
        ctx.response.body = getRes(0,list);
    }catch (e){
        console.log(e);
        ctx.response.body = getRes(2,e);
    }
})

content.post('/getall_id_type_byuser', async(ctx) => {
    try {
        let res = await query(`select itemid,type from content where user_id =? order by id desc`,ctx.user.id);
        
        ctx.response.body = getRes(0,res);
    }catch (e){
        console.log(e);
        ctx.response.body = getRes(2,e);
    }
})

content.post('/getlist', async(ctx) => {
    let orderby = ctx.request.body.orderby;
    let ordertype = ctx.request.body.ordertype;
    let queryObj = {
        user_id:ctx.user.id,
    };
    let whereObj = constructWhere(queryObj)
    try {
        let res = await query(`select * from content ${whereObj.where} order by ${orderby} ${ordertype}`,whereObj.values);
        for(var i=0;i<res.length;i++){
            var tmp = res[i];
            let qry = {
                user_id:ctx.user.id,
                content_id:tmp.itemid
            };
            let whereqry = constructWhere(qry);
            let mcn_res = await query(`select * from mcn ${whereqry.where}`,whereqry.values);
            
            tmp.mcn_data = mcn_res;
        }
        let obj = getRes(0,res);
        ctx.response.body = obj;
    }catch (e){
        console.log(e);
        ctx.response.body = getRes(2,e);
    }
})

content.post('/save_mcn_by_id', async(ctx) => {
    let qry = JSON.parse( JSON.stringify( ctx.request.body));
    delete qry.token;
    
    qry.user_id=ctx.user.id;
    let list = qry.list;
    try {
        let tranFunc = async (conn) => {//执行事务
            try{
                for(var i=0;i<list.length;i++){
                    var tmp = list[i];
                    let queryObjmcn = {
                        user_id:ctx.user.id,
                        "content_id":tmp.itemid
                    };
                    let whereObjmcn = constructWhere(queryObjmcn);
                    await query(`delete from mcn ${whereObjmcn.where}`,whereObjmcn.values);

                    let mcn_card_data = tmp.mcn_list;
                    for(var k=0;k<mcn_card_data.length;k++){
                        var mcn = mcn_card_data[k];
                        mcn.user_id = ctx.user.id,
                        mcn.mcn_isvail = 1;
                        console.log("***************mcn****************");
                        console.log(mcn);
                        await constInsert('mcn',mcn);
                    }
                }
                return Promise.resolve();
            }catch (e){
                return Promise.reject(e);
            }
        }
        await exeTrans(tranFunc);
        ctx.response.body = getRes(0);
    }catch (e){
        console.log(e);
        ctx.response.body = getRes(2,e);
    }
})

content.post('/save', async(ctx) => {
    let qry = JSON.parse( JSON.stringify( ctx.request.body));
    delete qry.token;
    
    qry.user_id=ctx.user.id;
    try {
        if(qry.mode=="content_add"){
            let queryObj = {
                itemid:qry.itemid,
                user_id:qry.user_id
            };
            let whereObj = constructWhere(queryObj);
            let total = await query(`select count(1) as cnt from content ${whereObj.where}`,whereObj.values);
            console.log(total);
            if(total[0].cnt>0){
                ctx.response.body = getRes(0,null);
            }else{
                delete qry.mode;
                let tranFunc = async (conn) => {//执行事务
                    try{
                        let mcn_card_data = qry.mcn_card_data;
                        delete qry.mcn_card_data;
                        await constInsert('content',qry);
                        for(var i=0;i<mcn_card_data.length;i++){
                            var mcn = mcn_card_data[i];
                            mcn.user_id = qry.user_id;
                            mcn.mcn_isvail = 1;
                            console.log("***************mcn****************");
                            console.log(mcn);
                            await constInsert('mcn',mcn);
                        }
                        return Promise.resolve('success');
                    }catch (e){
                        return Promise.reject(e);
                    }
                }
                await exeTrans(tranFunc);
                ctx.response.body = getRes(0);
            }
        }else if(qry.mode=="content_delete"){
            let queryObj = {
                itemid:qry.itemid,
                user_id:qry.user_id
            };
            let whereObj = constructWhere(queryObj);
            
            let queryObjmcn = {
                user_id:qry.user_id,
                "content_id":qry.itemid,
            };
            let whereObjmcn = constructWhere(queryObjmcn);
            let tranFunc = async (conn) => {//执行事务
                try{
                    await query(`delete from content ${whereObj.where}`,whereObj.values);
                    await query(`delete from mcn ${whereObjmcn.where}`,whereObjmcn.values);
                    return Promise.resolve('success');
                }catch (e){
                    return Promise.reject(e);
                }
            }
            await exeTrans(tranFunc);
            ctx.response.body = getRes(0);
        }else{
            ctx.response.body = getRes(3,null);
        }
    }catch (e){
        console.log(e);
        ctx.response.body = getRes(2,e);
    }
})

module.exports = content;